package org.bees.cms.web.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONArray;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.bees.cms.core.Domain;
import org.bees.cms.web.util.velocity.Context;
import org.bees.cms.web.util.velocity.element.Row;

public class Editor extends Tag {
	private static final long serialVersionUID = -4236922860583181103L;

	private String rows;
	private Domain domain;
	private List<Row> attributes = new ArrayList<Row>();

	@Override
	protected void before() throws Exception {
		JSONArray array = JSONArray.fromObject(rows == null || rows.trim().equals("") ? "[]" : rows);
		for (int i = 0; i < array.size(); i++) {
			Row row = new Row();
			row.from(array.getJSONObject(i));
			attributes.add(row);
		}
	}

	@Override
	protected void analyze(JspWriter writer) throws Exception {
		Template tlate = Velocity.getTemplate("editor.vm.html");
		Context context = context();
		context.put("domain", domain);
		context.put("rows", attributes);
		tlate.merge(context, writer);
	}

	@Override
	protected void after() throws Exception {
		rows = null;
		domain = null;
		attributes.clear();
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public Domain getDomain() {
		return domain;
	}

	public void setDomain(Domain domain) {
		this.domain = domain;
	}

	public List<Row> getAttributes() {
		return attributes;
	}

	public void setAttributes(List<Row> attributes) {
		this.attributes = attributes;
	}

}
